<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from 'vue';

import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

import '@wangeditor/editor/dist/css/style.css'; // 引入 css

const props = withDefaults(
    defineProps<{
        editor?: Record<string, any>;
        toolbar?: Record<string, any>;
    }>(),
    {
        editor: () => ({}),
        toolbar: () => ({}),
    },
);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const mode = ref('default');

// 内容 HTML
const content = defineModel();

const toolbarConfig = { ...props.toolbar };
const editorConfig = { placeholder: '请输入内容...', ...props.editor };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor) {
        editor?.destroy();
    }
});

const handleCreated = (editor: any) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<template>
    <div class="wangeditor" style="border: 1px solid var(--el-border-color); width: 100%">
        <Toolbar style="border-bottom: 1px solid var(--el-border-color)" :editor="editorRef" :default-config="toolbarConfig" :mode="mode" />
        <Editor style="height: calc(100vh - 350px)" v-model="content" :default-config="editorConfig" :mode="mode" @on-created="handleCreated" />
    </div>
</template>

<style scoped>
.wangeditor {
    --w-e-textarea-bg-color: var(--el-bg-color);
    --w-e-textarea-color: var(--el-text-color-regular);
    --w-e-toolbar-bg-color: var(--el-bg-color);
    --w-e-toolbar-border-color: var(--el-border-color);
    --w-e-toolbar-color: var(--el-text-color-regular);
    --w-e-toolbar-active-color: var(--el-text-color-regular);
    --w-e-toolbar-active-bg-color: var(--el-border-color);
}
</style>
